<?php

m2import("model/entity/WineryOrderFormEntryEntity.php");

/*
    Action configuration: 
        <conf:action mapping="wineryOrderFormEntry" class="WineryOrderFormEntryAction" methodmapping="true" bypassViewMapping="true">
        </conf:action>
*/
class WineryOrderFormEntryAction extends phpinchains_WebAction {

    function index (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        $this->dispatch("wineryOrderFormEntry::listing", $actionform);
    }

    function listPart (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        if ($actionform->get('redirect')) {
            $env->setSession('redirect_wineryorderformentry', $actionform->get('redirect'));
        }
        $entity = new WineryOrderFormEntryEntity($actionform, null);
        $pagesize = 20;
        $actionform->set("pagesize", $pagesize);
        
        $pagername = 'wineryorderformentryPager';
        // Save pager value in session
        if ($actionform->get($pagername)) {
            $env->setSession($pagername, $actionform->get($pagername));
        }
        $actionform->set($pagername, $env->getSession($pagername));
        $offset = ($env->getSession($pagername) ? ($pagesize * (int) $env->getSession($pagername)) - $pagesize : 0);
        
        $this->_loadReferenced('listing');

        // sorting
        $sortingname = 'wineryorderformentrySorting';
        if ($actionform->get($sortingname) && $entity->hasField($actionform->get($sortingname), true)) {
            $sorting = $env->getSession($sortingname);
            if ($sorting[0] == $actionform->get($sortingname) && (empty($sorting[1]) || $sorting[1] == 'asc')) {
               $sorting[1] = 'desc';
            } else {
                $sorting = array($actionform->get($sortingname));
            }
            $env->setSession($sortingname, $sorting);
        }
        if (!$env->getSession($sortingname)) {
            $env->setSession($sortingname, array (  0 => 'wofeno',  1 => 'asc',));
        }
        $actionform->set('sorting', $env->getSession($sortingname));
        
        $this->_handleFilter("searchformWineryOrderFormEntry");

        
        if ($actionform->get("searchformWineryOrderFormEntry")) {

            $searchdata = $actionform->get("searchformWineryOrderFormEntry");
            $searchfields = array();
            foreach($searchdata as $n => $v) {
                if (!strlen($v) || !$entity->hasField($n)) continue;
                if ($n == 'id') $n = 'R0.id';
                if ($v[0] == '*' || $v[strlen($v)-1] == '*') {
                    $searchfields[] = array($n, str_replace('*', '%', str_replace('%', '\%',$v)), 'LIKE');
                } else {
                    $searchfields[] = array($n, $v);
                }
            }
            $env->setSession("searchactiveWineryOrderFormEntry", true);
            $actionform->set("objList", $entity->findByFields($searchfields,
                'AND',
                array(
                'limit' => $pagesize,
                'joinreferenced' => true,
                'offset' => $offset,
                'orderby' => join(' ', $env->getSession($sortingname))
                )
            ));
            $count = $entity->findByFields($searchfields,
                'AND',
                array(
                'joinreferenced' => true,
                'fields' => "count(*) as count"
                )
            );

        } else {
            $env->setSession("searchactiveWineryOrderFormEntry", false);
            $actionform->set("objList", $entity->findByFields(array(), 'AND', array(
                'limit' => $pagesize, 
                'joinreferenced' => true,
                'offset' => $offset,
                'orderby' => join(' ', $env->getSession($sortingname))
                )
            ));
            $count = $entity->findByFields(array(), 'AND', array(
                'fields' => "count(*) as count",
                'joinreferenced' => true,
                )
            );
        }
        $actionform->set("count", $count['0']['count']);
        $actionform->set('wineryorderformentry_openCategories', $env->getSession("searchactiveWineryOrderFormEntry")?$env->getSession('searchactiveWineryOrderFormEntry_openCategories'):$env->getSession('wineryorderformentry_openCategories'));
    }

    function chooserListPart (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        if ($actionform->get('redirect')) {
            $env->setSession('redirect_chooserwineryorderformentry', $actionform->get('redirect'));
        }
        $entity = new WineryOrderFormEntryEntity($actionform, null);
        $pagesize = 20;
        $actionform->set("pagesize", $pagesize);

        $pagername = 'wineryorderformentryPager';
        // Save pager value in session
        if ($actionform->get($pagername)) {
            $env->setSession($pagername, $actionform->get($pagername));
        }
        $actionform->set($pagername, $env->getSession($pagername));
        $offset = ($env->getSession($pagername) ? ($pagesize * (int) $env->getSession($pagername)) - $pagesize : 0);
        
        $this->_loadReferenced('listing');

        // sorting
        $sortingname = 'wineryorderformentryChooserSorting';
        if ($actionform->get($sortingname) && $entity->hasField($actionform->get($sortingname), true)) {
            $sorting = $env->getSession($sortingname);
            if ($sorting[0] == $actionform->get($sortingname) && (empty($sorting[1]) || $sorting[1] == 'asc')) {
               $sorting[1] = 'desc';
            } else {
                $sorting = array($actionform->get($sortingname));
            }
            $env->setSession($sortingname, $sorting);
        }
        if (!$env->getSession($sortingname)) {
            $env->setSession($sortingname, array (  0 => 'wofeno',  1 => 'asc',));
        }
        $actionform->set('sorting', $env->getSession($sortingname));

        $this->_handleFilter("searchformWineryOrderFormEntry");

        
        if ($actionform->get("searchformWineryOrderFormEntry")) {

            $searchdata = $actionform->get("searchformWineryOrderFormEntry");
            $searchfields = array();
            foreach($searchdata as $n => $v) {
                if (!strlen($v) || !$entity->hasField($n)) continue;
                if ($n == 'id') $n = 'R0.id';
                if ($v[0] == '*' || $v[strlen($v)-1] == '*') {
                    $searchfields[] = array($n, str_replace('*', '%', str_replace('%', '\%',$v)), 'LIKE');
                } else {
                    $searchfields[] = array($n, $v);
                }
            }
            $env->setSession("searchactiveWineryOrderFormEntry", true);
            $actionform->set("objList", $entity->findByFields($searchfields,
                'AND',
                array(
                'limit' => $pagesize,
                'joinreferenced' => true,
                'offset' => $offset,
                'orderby' => join(' ', $env->getSession($sortingname))
                )
            ));
            $count = $entity->findByFields($searchfields,
                'AND',
                array(
                'joinreferenced' => true,
                'fields' => "count(*) as count"
                )
            );

        } else {
            $env->setSession("searchactiveWineryOrderFormEntry", false);
            $actionform->set("objList", $entity->findByFields(array(), 'AND', array(
                'limit' => $pagesize,
                'joinreferenced' => true,
                'offset' => $offset,
                'orderby' => join(' ', $env->getSession($sortingname))
                )
            ));
            $count = $entity->findByFields(array(), 'AND', array(
                'fields' => "count(*) as count",
                'joinreferenced' => true,
                )
            );
        }
        $actionform->set("count", $count['0']['count']);
        $actionform->set('wineryorderformentry_openCategories', $env->getSession("searchactiveWineryOrderFormEntry")?$env->getSession('searchactiveWineryOrderFormEntry_openCategories'):$env->getSession('wineryorderformentry_openCategories'));
    }


    function listing (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        $actionform->set('rootAction', 'wineryOrderFormEntry::listing');
    }

    function chooser (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        if ($actionform->get('openerfield')) {
            $env->setSession('wineryOrderFormEntry_openerfield', $actionform->get('openerfield'));
            $env->setSession('wineryOrderFormEntry_openertext', $actionform->get('openertext'));
            $env->setSession('wineryOrderFormEntry_databasefield', $actionform->get('databasefield'));
        }
        $actionform->set('openerfield', $env->getSession('wineryOrderFormEntry_openerfield'));
        $actionform->set('openertext', $env->getSession('wineryOrderFormEntry_openertext'));
        $actionform->set('databasefield', $env->getSession('wineryOrderFormEntry_databasefield'));

        $actionform->set('rootAction', 'wineryOrderFormEntry::chooser');
    }

    function createForm (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        $actionform->set('rootAction', 'wineryOrderFormEntry::createForm');
        $actionform->set("formAction", "create");
        $this->_loadReferenced('create');
        $actionform->set('wofeliter',"0.75");
        $actionform->set('wofeprice',"0.00");
        return "form";
    }
    
    function create (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        $actionform->set('rootAction', 'wineryOrderFormEntry::create');
        $this->constrainIncomingView("wineryOrderFormEntry/form", "form");
        if ($actionform->get("abort")) {
            $actionform->remove('id');
            $this->_formDispatch($actionform);
        } elseif ($this->validate()) {
            $entity = new WineryOrderFormEntryEntity($actionform, null);
            $formdata = $this->getFormdata("","",true);
            $entity->create($formdata);
            $actionform->remove('id');
            $env->setAttribute("actionmsg", "actionmsg_obj_created");
            $this->_formDispatch($actionform);
        } else {
            $this->dispatch("wineryOrderFormEntry::createForm", $actionform);
        }
    }

    function edit (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        $actionform->set('rootAction', 'wineryOrderFormEntry::edit');
        if ((int) $actionform->get("id")) {
            $entity = new WineryOrderFormEntryEntity($actionform, null);
            $actionform->set("formAction", "save");
            $actionform->set("editObj", $entity->findByPrimaryKey($actionform->get("id"), array('joinreferenced' => true)));
            $this->_loadReferenced('edit');
            return "form";
        } else {
            $env->setAttribute("actionmsg", "actionmsg_no_id_edit");
            $this->_formDispatch($actionform);
        }
    }
    
    function save (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        $this->constrainIncomingView("wineryOrderFormEntry/form", "form");
        if ($actionform->get("abort")) {
            $actionform->remove('id');
            $this->_formDispatch($actionform);
        } elseif ($this->validate()) {
            $entity = new WineryOrderFormEntryEntity($actionform, null);
            $formdata = $this->getFormdata("", "", true);
            $entity->update($formdata);
            $env->setAttribute("actionmsg", "actionmsg_obj_saved");
            if ($actionform->get("save")) {
                $actionform->remove('id');
                $this->_formDispatch($actionform);
            } else {
                $this->dispatch("wineryOrderFormEntry::edit", $actionform);
            }
        } else {
            $this->dispatch("wineryOrderFormEntry::edit", $actionform);
        }
    }

    function delete (env $env, phpinchains_ViewMapping $mapping, phpinchains_ActionForm $actionform) {
        if ((int) $actionform->get("id")) {
            $entity = new WineryOrderFormEntryEntity($actionform, null);
            
            $entity->delete((int) $actionform->get("id"));
            $actionform->remove('id');
            $env->setAttribute("actionmsg", "actionmsg_obj_deleted");
        } else {
            $env->setAttribute("actionmsg", "actionmsg_no_id_delete");
        }
        $this->_dispatchListing();
    }





    function _formDispatch ($actionform, $mode = '') {
        if ($this->env->getSession('redirect_'.$mode.'wineryorderformentry')) {
            $this->dispatch($this->env->getSession('redirect_'.$mode.'wineryorderformentry'), $actionform);
        } else {
            $this->setResponse('<strong>No redirect set!</strong>');
        }
    }

    function _dispatchListing ($mode = '') {
        $actionform = new phpinchains_Actionform();
        if ($this->env->getSession('redirect_'.$mode.'wineryorderformentry')) {
            $this->dispatch($this->env->getSession('redirect_'.$mode.'wineryorderformentry'), $actionform);
        } else {
            $this->dispatch('wineryOrderFormEntry::listing', $actionform);
        }
    }
    
    function _handleFilter ($name) {
        if ($this->actionform->get("wineryOrderFormEntryfilterReset") == "true") {
            $this->env->setSession($name, null);
            $this->env->setSession('searchactiveWineryOrderFormEntry_openCategories', null);
        }
        if ($this->actionform->get($name) && !$this->actionform->get('reset')) {
            $fields = $this->actionform->get($name);
            $set = false;
            if (is_array($fields)) {
                foreach ($fields as $n => $v) {
                    if (strlen($v)) {
                        $set = true;
                        break;
                    }
                }
            } elseif (strlen($fields)) {
                $set = true;
            }
            if ($set) {
                $this->env->setSession($name, $this->actionform->get($name));
            }
        }
        $this->actionform->set($name, $this->env->getSession($name));
    }
    
    public function exportCSV (env $env, phpinchains_ViewMapping $viewmapping, phpinchains_ActionForm $actionform) {
        header("Content-Type: text/csv; charset=utf-8");
        header('Content-Disposition: attachment; filename="export.csv"');
        $entity = new WineryOrderFormEntryEntity($actionform);
        $this->setResponse($entity->exportAllCSV(array(
        	'orderby'=>'wofcpos,wofeno', 
        	'joinreferenced'=>true,
        	'fields' => 'R0.id,wofcname,wofeno,wofeproduct,wofeyear,wofeliter,wofeprice,wofedescr'
        ),
        array(
        	'id' => 'ID',
        	'wofcname' => 'Kategorie',
        	'wofeno' => 'Produktnummer',
        	'wofeproduct' => 'Produktbezeichnung',
        	'wofeyear' => 'Jahrgang',
        	'wofeliter' => 'Liter',
        	'wofeprice' => 'Preis',
        	'wofedescr' => 'Produktbeschreibung'
        )
        ));
    }

    function _preProcess ($methodname, env $env, phpinchains_ViewMapping $viewmapping, phpinchains_ActionForm $actionform, $outsidecall) {
        // prevent setting rootAction from the outside
        if ($outsidecall) {
            $actionform->set('rootAction', '');
        }
        if (in_array($methodname, array("show", "edit")) && $outsidecall) {
            if ($actionform->get("id"))
                $env->setSession("selectedObj_wineryorderformentry_id", $actionform->get("id"));
        }
        
        // allow a preprocess method in the mix-ins
        if (method_exists($this, '_afterPreProcess')) {
            $this->_afterPreProcess($methodname, $env, $viewmapping, $actionform);
        }
    }

    function _loadReferenced ($caller) {
        
        $entity = new WineryOrderFormCatEntity($this->actionform, null);
        $this->actionform->set("objList_wofcat_id", $entity->findByFields(array(), "AND", array("fields"=>"R0.id,wofcname", 'orderby' => 'wofcname')));

    }

    function downloadBlob (env $env, phpinchains_ViewMapping $viewmapping, phpinchains_ActionForm $actionform) {
        $actionform->set('rootAction', 'downloadBlob');
        $actionform->set("content-disposition", "attachment");
        $this->_handleBlob ($env, $viewmapping, $actionform);
    }
            
    function viewBlob (env $env, phpinchains_ViewMapping $viewmapping, phpinchains_ActionForm $actionform) {
        $actionform->set('rootAction', 'viewBlob');
        $actionform->set("content-disposition", "inline");
        $this->_handleBlob ($env, $viewmapping, $actionform);
    }
            
    function _handleBlob (env $env, phpinchains_ViewMapping $viewmapping, phpinchains_ActionForm $actionform) {
        if ($id = (int) $actionform->get("id") && $field = $actionform->get("field")) {
            $entity = new WineryOrderFormEntryEntity($actionform, null);
            if (!$entity->isBlob($field)) return $this->setResponse("given field is not a blob!"); 
            $displayObj = $entity->findByPrimaryKey((int) $actionform->get("id"), array("fields" => "$field,{$field}_type,{$field}_size,{$field}_filename"));
            if ($actionform->get("content-disposition") == "attachment") {
                if($env->getServer("HTTP_USER_AGENT") and strpos($env->getServer("HTTP_USER_AGENT"),"MSIE"))
                    header("Content-Type: application/force-download");
                else
                    Header("Content-Type: application/octet-stream");
            } else {
                header("Content-Type: ".$displayObj["{$field}_type"]);
            }
            if (($resizeW = (int)$actionform->get('resize')) && preg_match('/image/i', $displayObj["{$field}_type"])) {
                try {
                    header("Content-disposition: ".$actionform->get("content-disposition")."; filename=".$displayObj["{$field}_filename"]);
                    $source = @imagecreatefromstring($displayObj[$field]);
                    $width  = @imagesx($source);
                    if ($width <= $resizeW) {
                        header("Content-Length: ".$displayObj["{$field}_size"]);
                        $this->setResponse($displayObj[$field]);
                        return;
                    }
                    $height = @imagesy($source);
                    $newwidth  = $resizeW;
                    $newheight = round($height * ($resizeW / $width));
                    $thumb = imagecreatetruecolor($newwidth, $newheight);
                    imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
                    if (preg_match('/gif$/i', $displayObj["{$field}_type"])) {
                        imagegif($thumb);
                    } elseif (preg_match('/png$/i', $displayObj["{$field}_type"])) {
                        imagepng($thumb);
                    } else {
                        imagejpeg($thumb);
                    }
                    $this->setResponse('');
                } catch (Exception $e) {}
            } else {
                header("Content-Length: ".$displayObj["{$field}_size"]);
                header("Content-disposition: ".$actionform->get("content-disposition")."; filename=".$displayObj["{$field}_filename"]);
                $this->setResponse($displayObj[$field]);
            }
        } else {
            $env->setAttribute("actionmsg", "actionmsg_no_id_download");
            $this->dispatch("%s::listing", $actionform);
        }
    }


    public function toggleVisibility (env $env, phpinchains_ViewMapping $viewmapping, phpinchains_ActionForm $actionform) {
        if ($actionform['id']) {
            $entity = new WineryOrderFormEntryEntity($actionform);
            $obj = $entity->findByPrimaryKey($actionform['id']);
            $update = array('id'=>$actionform['id']);
            if ($obj['wofevisible']=='Y') {
                $update['wofevisible'] = 'N';
            } else {
                $update['wofevisible'] = 'Y';
            }
            $entity->update($update);
        }
        $this->dispatch('wineryOrderFormEntry::listing', $actionform);
    }


}
    

?>